package cn.hackcloud.mutithread.mutilthread.lock2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyService {
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	public void await() {
		try {
			lock.lock();
			System.out.println("begin await时间为：" + System.currentTimeMillis());
			condition.await();
			System.out.println("end await时间为：" + System.currentTimeMillis());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void awaitB() {
		try {
			lock.lock();
			System.out.println("begin await时间为：" + System.currentTimeMillis());
			condition.await();
			System.out.println("end await时间为：" + System.currentTimeMillis());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void signalAll() {
		try {
			lock.lock();
			System.out.println("signal时间为：" + System.currentTimeMillis());
			condition.signalAll();
		} finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		MyService myService = new MyService();
		MyThread t1 = new MyThread(myService);
		t1.start();
		MyThreadB t2 = new MyThreadB(myService);
		t2.start();
		Thread.sleep(2000);
		myService.signalAll();
	}
}
